<?php

$langs     = $REQUEST->getLangAll();
$langs_ids = array();
foreach($langs AS $l) $langs_ids[$l['id']] = $l;

if(session::user() && session::user()->hasRole('ADMIN'))
{
   switch ($action)
   {
      case 1:
         # GET TRANSLATIONS FOR GRID

         $items = !empty($_GET['rows']) && is_numeric($_GET['rows']) ? $_GET['rows'] : config::read('items');
         paginator::setItemsOnPage($items);

         $where = 'WHERE `lang` = '. $REQUEST->getLangDefaultId();
         if(session::user()->id != 1)
         {
            $where .= ' AND `sys` = "0"';
         }
         if(!empty($_GET['searchField']) && !empty($_GET['searchString']))
         {
            $field = $_GET['searchField'] == 'name' || $_GET['searchField'] == 'key' ? $_GET['searchField'] : 'value';
            $operation = $_GET['searchOper'] == 'eq' ? 'eq' : 'cn';

            if($field == 'value')
            {
               $where .= ' AND `id` IN (SELECT `id` FROM `meccano_translations` WHERE `value` ';
               $where .= $operation == 'cn' ? ' LIKE "%'. mysql_real_escape_string($_GET['searchString']) .'%"' : ' = "'. mysql_real_escape_string($_GET['searchString']) .'"';
               $where .= ')';
            } else
            {
               $where .= ' AND `'. $field .'`';
               $where .= $operation == 'cn' ? ' LIKE "%'. mysql_real_escape_string($_GET['searchString']) .'%"' : ' = "'. mysql_real_escape_string($_GET['searchString']) .'"';
            }
         }


         if(!empty($_GET['sidx']) && ($_GET['sidx'] == 'name' || $_GET['sidx'] == 'key'))
         {
            $order = '`'. $_GET['sidx'] .'`'. ($_GET['sord'] == 'asc' ? ' ASC' : ' DESC');
         } else
         {
            $order = '`name` ASC, `key` ASC';
         }

         $sql = 'SELECT SQL_CALC_FOUND_ROWS *
            FROM `meccano_translations` ' . $where . '
            ORDER BY '. $order .'
            LIMIT '. ((paginator::getCurrentPage() - 1) * paginator::getItemsOnPage ()) .', '. paginator::getItemsOnPage();
         //echo $sql;
         $DB->sql = $sql;
         $vars = $DB->DB_Fetch();
         $DB->sql = 'SELECT FOUND_ROWS()';
         $found = $DB->DB_FetchFlat();
         $found = reset($found);
         paginator::setPages($found);

         $pages = paginator::getPages();
         $result          = array();
         $result['page']  = paginator::getCurrentPage();
         $result['total'] = $pages['pages'];
         $result['records'] = $pages['found'];

         for($i=0, $t=sizeof($vars); $i<$t; $i++)
         {
            $tmp = array();
            $tmp['id'] = $vars[$i]['id'];
            $tmp['cell'] = array($vars[$i]['id'], $vars[$i]['name'], $vars[$i]['key'], $vars[$i]['value'], $vars[$i]['sys']);
            $result['rows'][] = $tmp;
         }


         echo json_encode($result);
         exit();
         break;




      case 2:
         # INLINE OPERATIONS IN GRID, DELETE OR SWITCH system

         if(!empty($_POST['oper']) && !empty($id) && session::user()->id == 1)
         {
            $respond = FALSE;

            switch($_POST['oper'])
            {
               # Delete Item
               case 'del':

                  $DB->sql = 'DELETE FROM `meccano_translations` WHERE `id` = "'. $id .'"';
                  $respond = $DB->DB_Query();
                  break;

               # Set / Unset system flag
               case 'edit':
                  $system = empty($_POST['system']) ? 0 : 1;
                  $DB->sql = 'UPDATE `meccano_translations` SET `sys` = "'. $system .'" WHERE `id` = "'. $id .'"';
                  $respond = $DB->DB_Query();
                  break;
            }

            echo json_encode($respond);
         }
         exit();
         break;



      case 3:
         # GET VAR FOR EDITION IN A GUI FORM

         $respond = FALSE;
         if(!empty($id))
         {
            $sql = 'SELECT * FROM `meccano_translations` WHERE `id` = "'. $id .'"';
            if(session::user()->id != 1)
            {
               $sql .= ' AND `sys` = "0"';
               $sql .= ' AND `lang` IN ('. implode(', ', array_keys($langs_ids)) .')';
            }
            $DB->sql = $sql;
            $vars = $DB->DB_Fetch();

            if(!empty($vars))
            {
               $respond = array();
               for($i=0, $t=sizeof($vars); $i<$t; $i++)
               {
                  if(empty($langs_ids[$vars[$i]['lang']])) continue;
                  
                  if($i == 0)
                  {
                     $respond['id']     = $vars[$i]['id'];
                     $respond['name']   = $vars[$i]['name'];
                     $respond['key']    = $vars[$i]['key'];
                     $respond['system'] = $vars[$i]['sys'];
                  }

                  $respond['value'][] = array(
                     'lang_id'    =>$vars[$i]['lang'],
                     'lang_alias' =>$langs_ids[$vars[$i]['lang']]['title'],
                     'value'      =>$vars[$i]['value']
                  );
               }
            }
         }
         echo json_encode($respond);
         exit();
         break;



      case 4:
         # SAVE TRANSLATION FROM GUI FORM

         $respond = FALSE;
         if(!empty($_POST['f']))
         {
            if(session::user()->id != 1 && !empty($id))
            {
               if(!empty($_POST['f']['value']) && is_array($_POST['f']['value']))
               {
                  foreach($_POST['f']['value'] AS $l=>$value)
                  {
                     if(isset($langs_ids[$l]))
                     {
                        $sql = 'UPDATE `meccano_translations` SET `value` = "%s" WHERE `id` = "'. $id .'" AND `lang` = "'. $l .'"';
                        $DB->DB_QueryBuilder($sql, array($value));
                        $respond = $DB->DB_Query();
                     }
                  }
               }
            } elseif(session::user()->id == 1 && !empty($_POST['f']['name']) && $FILTER->isValidAlpha($_POST['f']['name']))
            {
               $key    = !empty($_POST['f']['key']) && $FILTER->isValidAlpha($_POST['f']['key']) ? $_POST['f']['key'] : "";
               $system = !empty($_POST['f']['system']) ? 1 : 0;
               $name   = $_POST['f']['name'];

               # ADD NEW TRANSLATION
               $id        = empty($id) ? $DB->DB_GetNextID('id', 'meccano_translations') : $id;
               $sql_query = 'REPLACE INTO `meccano_translations` (`id`, `lang`, `name`, `key`, `value`, `sys`) VALUES (';
               $sql_vars  = array();
               $sql       = array();
               foreach($_POST['f']['value'] AS $l=>$value)
               {
                  if(isset($langs_ids[$l]))
                  {
                     $sql[] = $id .', '. $l .', "%s", "%s", "%s", "'. $system .'"';
                     array_push($sql_vars, $name, $key, $value);
                  }
               }

               if(!empty($sql))
               {
                  $DB->DB_QueryBuilder($sql_query . implode('),(', $sql) .')', $sql_vars);
                  //echo $DB->sql;
                  $respond = $DB->DB_Query();
               }
            }
         }

         echo json_encode($respond);
         exit();
         break;


      case 5:
         # EXPORT TRANSLATIONS (INTO CSV)

         $csv = gettext::exportCSV();

         /*
         $fp = fopen($csv_file, 'w');
         $csv_headers = array('KEY (do not edit)');
         foreach($langs AS $l)
         {
            $csv_headers[] = $l['title'] .'['. $l['iso'] .']';
         }

         fputcsv($fp, $csv_headers);

         $DB->sql = 'SELECT * FROM `meccano_translations` ORDER BY `id`, `lang`';
         $DB->DB_Fetch();

         $vars = array();
         for($i=0, $t=$DB->rows; $i<$t; $i++)
         {
            $vars[$DB->fetched[$i]['id']][$DB->fetched[$i]['lang']] = $DB->fetched[$i]['value'];
         }

         fclose($fp);
          */

         header('Content-Type: text/csv');
         header('Content-Disposition: attachment;filename="translations.csv"');
         header('Cache-Control: max-age=0');
         header('Content-Length: '. strlen($csv));
         print $csv;
         exit();
         
         break;



      default:
         $SMARTY->assign('c', $TREE->getNode(6));
   }

   $layout = 'translation.html';
} else
{
   if (session::user())
   {
      $ErrorHandler->setError(
         array(
         'code' => 'access',
         'varkey' => 'access_denied'
         )
      );
   }
   $layout = 'login.html';
}